import Vue from 'vue'
import Router from 'vue-router'
// import http from '@/utils/request'
import { isURL } from '@/utils/validate'
import store from '@/store'
import { fixedRouter } from './fixedRouter'
Vue.use(Router)

export const pageRoutes = [
  // {
  //   path: '/404',
  //   component: () => import('@/views/pages/404'),
  //   name: '404',
  //   meta: { title: '404 not find' },
  //   beforeEnter (to, from, next) {
  //     if (/__.*/.test(to.href)) {
  //       return next(to.redirectedFrom.replace(/__.*/, ''))
  //     }
  //     next()
  //   }
  // },
  // { path: '/loginAsAccount', caseSensitive: false, component: () => import('@/views/pages/loginAsAccount'), name: 'loginAsAccount', meta: { title: 'loginAsAccount' } },
  // { path: '/registAsAccount', component: () => import('@/views/pages/registAsAccount'), name: 'registAsAccount', meta: { title: 'registAsAccount1' } },
  { path: '/login', component: () => import('@/views/modules/demo/login1'), name: 'login', meta: { title: 'login' } },
  // { path: '/new-login', component: () => import('@/views/pages/login/index'), name: 'new-login', meta: { title: 'new-login' } },
  // { path: '/regist', component: () => import('@/views/pages/regist'), name: 'regist', meta: { title: 'regist' } },
  // { path: '/feedback', component: () => import('@/views/pages/feedback'), name: 'feedback', meta: { title: 'feedback' } },
  { path: '/userForm', component: () => import('@/views/pages/userForm'), name: 'userForm', meta: { title: 'userForm' } },
  { path: '/publicReport', component: () => import('@/views/pages/publicReport'), name: 'publicReport', meta: { title: 'publicReport' } },
  // { path: '/ntreport', component: () => import('@/views/pages/ntreport'), name: 'ntreport', meta: { title: 'ntreport' } },
  // { path: '/Attendance', caseSensitive: false, name: 'Attendance', meta: { title: 'Attendance' }, redirect: { path: '/Apps?appId=1464133492681084928' } },
  { path: '/present', component: () => import('@/views/modules/mspbots/reports/present-layout'), name: 'present', meta: { title: 'Present' } },
  // { path: '/portal', component: () => import('@/views/modules/mspbots/client-portal/portal'), name: 'portal', meta: { title: 'portal' } },
  // { path: '/portalDashboard', component: () => import('@/views/modules/mspbots/client-portal/portal-layout'), name: 'portalDashboard', meta: { title: 'portalDashboard' } },
  // { path: '/portal-404', component: () => import('@/views/modules/mspbots/client-portal/components/portal-404'), name: 'portal-404', meta: { title: '404' } },
  { path: '/desktop', component: () => import('@/views/modules/mspbots/desktop-app/desktop-index'), name: 'desktop', meta: { title: 'Desktop' } },
  { path: '/print', component: () => import('@/components/gadget/crud-form-plus/components/form-view-print'), name: 'print', meta: { title: 'Print' } }
  
  // ...fixedRouter
]

export const moduleRoutes = {
  path: '/',
  component: () => import('@/views/main'),
  name: 'main',
  redirect: { name: 'home' },
  meta: { title: 'main' },
  children: [
    { path: '/home', component: () => import('@/views/modules/mspbots/dashboard/index?pageid=home'), name: 'home', meta: { title: 'Desktop', isTab: true } },
    /// /views/modules/mspbots/dashboard/index?pageid=home
    {
      path: '/404',
      component: () => import('@/views/pages/404'),
      name: '404',
      meta: { title: '404 not find' },
      beforeEnter (to, from, next) {
        if (/__.*/.test(to.href)) {
          return next(to.redirectedFrom.replace(/__.*/, ''))
        }
        next()
      }
    }
  ]
}
export function addDynamicRoute (routeParams, router, noJump) {
  var routeName = routeParams.routeName
  var dynamicRoute = window.SITE_CONFIG['dynamicRoutes'].filter(item => item.name === routeName)[0]
  if (dynamicRoute) {
    return router.push({ name: routeName, params: routeParams.params })
  }
  dynamicRoute = {
    path: routeName,
    // component: () => import(`@/views/modules/${routeParams.path}`),
    component: () => Promise.resolve(require(`@/views/modules/${routeParams.path}`).default),
    name: routeName,
    meta: {
      ...window.SITE_CONFIG['contentTabDefault'],
      menuId: routeParams.menuId,
      title: `${routeParams.title}`
    }
  }
  router.addRoutes([
    {
      ...moduleRoutes,
      name: `main-dynamic__${dynamicRoute.name}`,
      children: [dynamicRoute]
    }
  ])
  window.SITE_CONFIG['dynamicRoutes'].push(dynamicRoute)
  if (!noJump) {
    router.push({ name: dynamicRoute.name, params: routeParams.params, query: routeParams.query })
  }
}
const router = new Router({
  mode: 'history',
  scrollBehavior: () => ({ y: 0 }),
  routes: pageRoutes.concat(moduleRoutes)
})
router.beforeEach((to, from, next) => {
  if (to.path === '/NPS') {
    next({ path: '/userForm', query: { ...to.query, formCode: '1541637280530305024', autoSubmit: 'true' } })
  }
  // if (to.name === 'mspbots-connector-config-index' || to.name === 'mspbots-work-schedule-index') {

  //   store.state.GetStarted.dialogStatus = true
  //   store.state.GetStarted.steps = 1
  // }
  // to.fullPath !== '/login' && to.fullPath !== '/home' && !to.fullPath.includes('home')
  if (!sessionStorage.getItem('isLoginRouterPath') && to.fullPath !== '/login' && to.fullPath !== '/loginAsAccount') {
    sessionStorage.setItem('isLoginRouterPath', to.fullPath)
  }

  window.document.title = to.meta.title || 'MSPbots'
  if (window.SITE_CONFIG['dynamicMenuRoutesHasAdded'] || fnCurrentRouteIsPageRoute(to, pageRoutes)) {
    return next()
  }
  Vue.prototype.$interface.system.generalListApi().then(({ data: res }) => {
    // http.get('/sys/dict/type/all')
    if (res.code !== 0) {
      return
    }
    window.SITE_CONFIG['dictList'] = res.data
    getNavLists()
  }).catch(() => { })
  function getNavLists () {
    const params = {}
    if (sessionStorage.getItem('loginAsUserId')) {
      params.loginAsUserId = sessionStorage.getItem('loginAsUserId')
    }
    if (sessionStorage.getItem('loginAsRoleId')) {
      params.loginAsRoleId = sessionStorage.getItem('loginAsRoleId')
    }
    Vue.prototype.$interface.system.navMenuListApi(params).then(({ data: res }) => {
      // http.get('/sys/menu/nav')
      if (res.code !== 0) {
        Vue.prototype.$message.error(res.msg)
        return next({ name: 'login' })
      }
      window.SITE_CONFIG['menuList'] = res.data
      fnAddDynamicMenuRoutes(window.SITE_CONFIG['menuList'])
      store.commit('SET_API_LOAD_TEXT', 'Loading')
      store.commit('SET_API_LOAD_STATUS', false)
      next({ ...to, replace: true })
    }).catch(() => {
      next({ name: 'login' })
      store.commit('SET_API_LOAD_STATUS', false)
    })
  }
})

/**
 * @param {*} route
 * @param {*} pageRoutes
 */
function fnCurrentRouteIsPageRoute (route, pageRoutes = []) {
  var temp = []
  for (var i = 0; i < pageRoutes.length; i++) {
    if (route.path === pageRoutes[i].path || pageRoutes[i].path.indexOf(route.path) > 0) {
      return true
    }
    if (pageRoutes[i].children && pageRoutes[i].children.length >= 1) {
      temp = temp.concat(pageRoutes[i].children)
    }
  }
  return temp.length >= 1 ? fnCurrentRouteIsPageRoute(route, temp) : false
}

/**
 * @param {*} menuList
 * @param {*} routes
 */
export function fnAddDynamicMenuRoutes (menuList = [], routes = []) {
  var temp = []
  for (var i = 0; i < menuList.length; i++) {
    if (!menuList[i].name) {
      console.log(menuList[i])
      continue
    }
    if (menuList[i].name === 'Bots' && menuList[i].url === 'mspbots/bots-bak/my-bots/index') {
      menuList[i].children.forEach(element => {
        element.isbot = true
      })
    }
    if (menuList[i].children && menuList[i].children.length >= 1) {
      temp = temp.concat(menuList[i].children)
      if (menuList[i].children && menuList[i].children.length >= 1 && menuList[i].url && !menuList[i].hideFromMenu && menuList[i].name) {
        let tList = { ...menuList[i] }
        tList.children = []
        temp.push(tList)
      }
      continue
    }

    var tempQuery = ''
    try {
      tempQuery = JSON.parse(menuList[i].param)
    } catch (e) {
      tempQuery = ''
    }

    var route = {
      path: '',
      component: null,
      name: '',
      query: tempQuery,
      meta: {
        ...window.SITE_CONFIG['contentTabDefault'],
        menuId: menuList[i].id,
        title: menuList[i].name,
        param: menuList[i].param ? menuList[i].param : ''
      }
    }
    if (menuList[i].isbot) route.isbot = true
    // eslint-disable-next-line
    let URL = (menuList[i].url || '').replace(/{{([^}}]+)?}}/g, (s1, s2) => eval(s2))
    if (isURL(URL)) {
      if (menuList[i].name) {
        route['path'] = menuList[i].name.replace(/\s+/g, '')
      }
      route['name'] = URL.replace(/\//g, '-') + (menuList[i].param ? '$' + menuList[i].param.replace(/^\s*|\s*$/g, '') : '')
      route['meta']['iframeURL'] = URL
    } else {
      URL = URL.replace(/^\//, '').replace(/_/g, '-')
      if (menuList[i].name) {
        route['path'] = menuList[i].name.replace(/\s+/g, '')
      }
      route['name'] = URL.replace(/\//g, '-') + (menuList[i].param ? '$' + menuList[i].param.replace(/^\s*|\s*$/g, '') : '')
      route['component'] = () => Promise.resolve(require(`@/views/modules/${URL}`).default)
    }
    routes.push(route)
  }
  if (temp.length >= 1) {
    return fnAddDynamicMenuRoutes(temp, routes)
  }
  for (let index = 0; index < routes.length; index++) {
    const element = routes[index]
    // report view page & scorecard view page
    if (element.name.indexOf('mspbots-reports-report-layout${"pageid":"') !== -1 || element.name.indexOf('mspbots-reports-scorecard-layout${"pageid":"') !== -1 || element.name.indexOf('mspbots-reports-report-layout-autoTask${"pageid":"') !== -1) {
      element.path = 'dashboard-' + element.meta.menuId

      // element.meta.keepAlive = false
    }
    // dataset view page
    if (element.name.indexOf('mspbots-dataset-dataset-view${"pageid":"') !== -1) {
      element.path = 'dataset-' + element.meta.menuId
    }
    // bots view page
    if (element.name.indexOf('mspbots-dashboard-index${"pageid":"') !== -1 && element.isbot) {
      element.path = 'bot-' + element.meta.menuId
      // element.meta.keepAlive = false
    }
  }
  router.addRoutes([
    {
      ...moduleRoutes,
      name: 'main-dynamic-menu',
      children: routes
    },
    { path: '*', redirect: { name: '404' } }
  ])
  router.addRoutes(fixedRouter)
  window.SITE_CONFIG['dynamicMenuRoutes'] = routes
  window.SITE_CONFIG['dynamicMenuRoutesHasAdded'] = true
}
// router Tool
// Tool start
router.afterEach((to) => {
  var userName = store.state.user.username
  if (userName) {
    const temp = store.state.app.isSwitchTenant ? store.state.app.isSwitchTenant : sessionStorage.getItem('isSwitchTenant')
    const params = {
      url: to.fullPath,
      loginAs: temp || 0
    }
    if (to.path !== '/portal') {
      Vue.prototype.$interface.um.poststatRouteAPI(params)
    }
  }
})
// Tool end
export default router
